<script setup>
import {nextTick, onMounted, reactive, toRaw} from "vue";
import {ref} from "vue";
import api from "@/util/api.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
import {Plus, Search, RefreshRight, Delete, Edit, CirclePlus} from "@element-plus/icons-vue";
import baseUrl from "@/util/constant.js";
import {getJwt} from "@/api/jwt.js";

onMounted(async () => {
  findAll();
})
let coach = ref();
let coachPi = reactive({
  pageNo: 1,
  pageSize: 20,
  total: 0
})
let coachList = ref({
  name: null,
  gender: null,
  phone: null,
  hireDateRange: []
});
let coachForm = ref();
let tables = ref();
let coachTitle = ref();
let coachShow = ref(false);
let coachAddForm = ref({
  name: null,
  gender: null,
  hireDate: null,
  specialty: null,
  phone: null,
  email: null,
  avatar: null,
  status: null
});
let mode = "add";

const headers={
  "jwt":getJwt()
};
//查询
async function findAll(pageNo = 1, pageSize = 10) {
  let params = toRaw(coachList.value);
  if (params.hireDateRange && params.hireDateRange.length === 2) {
    params.hireDateFrom = params.hireDateRange[0];
    params.hireDateTo = params.hireDateRange[1];
    delete params.hireDateRange;
  }
  let resp = await api({
    url: "/coach",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    }
  });
  coach.value = resp.data.records;
  coachPi.total = resp.data.total;
  coachPi.pageSize = resp.data.size;
  coachPi.pageNo = resp.data.current;

}

// 分页页码变化
function handlePageChange(pageNo) {
  findAll(pageNo, coachPi.pageSize)
}

// 每页条数变化
function handleSizeChange(pageSize) {
  coachPi.pageSize = pageSize;
  findAll(1, pageSize); // 重置到第一页
}

//重置
function reset() {
  coachForm.value.resetFields();
  findAll();
}

//单击表格选中
function tableRowClick(row) {
  tables.value.toggleRowSelection(row);
}

//删除按钮
function remove() {
  let rows = tables.value.getSelectionRows();
  if (rows === null || rows.length === 0) {
    ElMessage.warning("请选择要删除的行");
  } else {
    ElMessageBox.confirm(
        '确定要删除吗?',
        '警告',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    ).then(() => {
      let ids = rows.map(row => row.id)
      removeByIds(ids);
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
  }
}

//执行删除
async function removeByIds(ids) {
  let resp = await api({
    url: "/coach",
    method: "delete",
    data: ids
  });
  if (resp.success) {
    ElMessage.success("删除成功,共删除" + resp.data + "条数据")
    findAll();
  } else {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  }
}

//行内删除
function deleteById(row) {
  ElMessageBox.confirm(
      '确定要删除吗?',
      '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  ).then(() => {
    removeByIds([row.id]);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  })
}

// 新增按钮
function add() {
  coachTitle.value = "新增会员";
  coachShow.value = true;
  mode = "add";
  coachAddForm.value = ({
    name: null,
    gender: '男',
    hireDate: null,
    specialty: null,
    phone: null,
    email: null,
    avatar: null,
    status: null,
  })
}

//判断编辑和新增
function doSubmit() {
  if (mode === "add") {
    subAdd();
  } else if (mode === "edit") {
    subEdit();
  }
}

// 提交新增
function subAdd() {
  let params = toRaw(coachAddForm.value);
  let resp = api({
    url: "/coach",
    method: "post",
    data: params
  }).then(resp => {
    if (resp.success) {
      coachShow.value = false;
      findAll();
      ElMessage.success("新增成功");
    } else {
      ElMessage.error(resp.msg || "新增失败")
    }
  }).catch(resp => {
    ElMessage.error("请求新增失败")
  });
}

function edit(row) {
  coachTitle.value = "编辑会员";
  coachShow.value = true;
  mode = "edit";
  nextTick(() => {
    coachAddForm.value = cloneDeep(toRaw(row))
    coachAddForm.value.status = coachAddForm.value.status === 1 ? "1" : "0";
  })
}

//提交编辑
function subEdit() {
  let params = toRaw(coachAddForm.value);
  let resp = api({
    url: "/coach",
    method: "put",
    data: params
  }).then(resp => {
    if (resp.success) {
      coachShow.value = false;
      findAll(coachPi.pageNo, coachPi.pageSize);
      ElMessage.success("修改成功");
    } else {
      ElMessage.error(resp.msg || "修改失败")
    }
  }).catch(resp => {
    ElMessage.error(resp.msg || "修改失败")
  })
}


function handleAvatarSuccess(resp) {
  coachAddForm.value.avatar = resp.data;
}

</script>
<template>
  <div id="search">
    <el-form :inline="true" :model="coachList" class="demo-form-inline" ref="coachForm">
      <el-form-item label="姓名" prop="name">
        <el-input style="width: 150px" v-model="coachList.name" placeholder="请输入姓名"/>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="coachList.gender" style="width: 100px" empty-values="[null]" clearable>
          <el-option label="请选择" value=""/>
          <el-option label="男" value="男"/>
          <el-option label="女" value="女"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入职日期" prop="hireDateRange">
        <el-date-picker
            type="daterange"
            placeholder="-"
            start-placeholder="日期从"
            end-placeholder="日期止"
            v-model="coachList.hireDateRange"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input style="width: 150px" v-model="coachList.phone" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="findAll()">
          <el-icon><Search /></el-icon>查询
        </el-button>
        <el-button type="warning" @click="reset">
          <el-icon><RefreshRight /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div id="action">
    <el-button type="primary" @click="add">
      <el-icon><CirclePlus /></el-icon>新增
    </el-button>
    <el-button type="danger" @click="remove">
      <el-icon><Delete /></el-icon>批量删除
    </el-button>
  </div>
  <div id="table">
    <el-table
        :data="coach"
        style="width: 100%"
        border
        stripe
        class="tbl"
        ref="tables"
        @row-click="tableRowClick"
        :row-class-name="({row, rowIndex}) => rowIndex % 2 === 0 ? 'even-row' : 'odd-row'"
    >
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="id" label="ID" width="100" fixed/>
      <el-table-column prop="name" label="姓名" width="120" fixed/>
      <el-table-column prop="avatar" label="照片" width="120">
        <template #default="scope">
          <div class="img" :style="'background-image: url('+scope.row.avatar+')'"></div>
        </template>
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="120"/>
      <el-table-column prop="hireDate" label="入职日期" width="120"/>
      <el-table-column prop="status" label="状态" width="180">
        <template #default="scope">
          <el-tag v-if="scope.row.status===1" type="primary" class="status-tag active">在会</el-tag>
          <el-tag v-else type="danger" class="status-tag inactive">退会</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机" width="220"/>
      <el-table-column prop="email" label="邮箱" width="220"/>
      <el-table-column prop="specialty" label="擅长专业" width="220"/>
      <el-table-column fixed="right" label="操作" min-width="200">
        <template #default="scope">
          <el-button type="danger" size="default" @click.stop="deleteById(scope.row)">
            <el-icon><Delete /></el-icon>删除
          </el-button>
          <el-button type="primary" size="default" @click.stop="edit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div id="pagination">
    <el-pagination
        v-model:current-page="coachPi.pageNo"
        v-model:page-size="coachPi.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="coachPi.total"
        background=true
        @change="handlePageChange"
        @size-change="handleSizeChange"
    />
  </div>

  <el-dialog :title="coachTitle" width="600" v-model="coachShow">
    <el-form :model="coachAddForm" label-width="100" label-position="right">
      <el-row>
        <el-col :span="14">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="coachAddForm.name" placeholder="请输入姓名" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="性别：" prop="gender">
            <el-select v-model="coachAddForm.gender" style="width: 100px" empty-values="[null]" placeholder="请选择：">
              <el-option label="请选择" value=""/>
              <el-option label="男" value="男"/>
              <el-option label="女" value="女"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=10>
          <el-upload class="avatar-uploader" action="/api/coach/avatar"
                     :show-file-list="false" :on-success="handleAvatarSuccess" :headers="headers">
            <div v-if="coachAddForm.avatar" :style="'background-image: url('+coachAddForm.avatar+')'"
                 class="avatar"></div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-col>
      </el-row>
      <el-form-item label="入职日期" prop="hireDate">
        <el-date-picker v-model="coachAddForm.hireDate" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择入职日期"/>
      </el-form-item>
      <el-form-item label="擅长专业" prop="specialty">
        <el-input v-model="coachAddForm.specialty" placeholder="请输入擅长专业" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="coachAddForm.phone" placeholder="请输入手机号" autocomplete="off"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="coachAddForm.email" placeholder="请输入邮箱" autocomplete="off"/>
      </el-form-item>
      <div class="status-radio-group">
        <el-radio-group v-model="coachAddForm.status">
          <el-radio-button label="在会" value="1" />
          <el-radio-button label="退会" value="0" />
        </el-radio-group>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="coachShow = false">取消</el-button>
        <el-button type="primary" @click="doSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
#pagination {
  margin-top: 6px;
}

#action {
  margin-bottom: 6px;
}

.avatar-uploader {
  border: 1px solid #dfdede;
  width: 120px;
  height: 110px;
  margin-left: 56px;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-uploader:hover {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.avatar{
  width: 120px;
  height: 110px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}
.avatar-uploader-icon {
  font-size: 20px;
  justify-content: center;
  align-items: center;
  width: 110px;
  height: 90px;
  display: flex;
  color: #909399;
}

.img {
  width: 100%;
  height: 100px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  border-radius: 4px;
  transition: transform 0.3s ease;
}

.img:hover {
  transform: scale(1.05);
}

/* 全局样式优化 */
:deep(body) {
  background-color: #f5f7fa;
  color: #303133;
  font-family: "Helvetica Neue", Arial, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
  line-height: 1.5;
}

/* 标题样式 */
h1 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2329;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

/* 搜索区域样式 */
#search {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  transition: box-shadow 0.3s ease;
}

#search:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

:deep(#search .el-form-item) {
  margin-bottom: 12px;
}

:deep(#search .el-input__inner),
:deep(#search .el-select__inner) {
  border-radius: 4px;
  transition: all 0.2s ease;
}

:deep(#search .el-input__inner:focus),
:deep(#search .el-select__inner:focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 操作按钮区域 */
#action {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

:deep(#action .el-button) {
  border-radius: 4px;
  transition: all 0.2s ease;
}

:deep(#action .el-button):hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

/* 表格样式 */
#table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

:deep(.tbl) {
  border-radius: 4px;
}

:deep(.tbl th) {
  background-color: #f7f8fa;
  font-weight: 500;
  color: #4e5969;
  height: 48px;
}

:deep(.tbl td) {
  height: 52px;
  transition: background-color 0.2s ease;
}

:deep(.tbl .even-row td) {
  background-color: #fcfcfc;
}

:deep(.tbl .odd-row td) {
  background-color: #fff;
}

:deep(.tbl .el-table__row:hover td) {
  background-color: #f0f7ff !important;
}

:deep(.tbl .el-table__cell) {
  padding: 8px 0;
}

/* 分页样式 */
#pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

:deep(.el-pagination) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-pagination button) {
  border-radius: 4px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 2px;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 6px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: #f7f8fa;
  padding: 14px 20px;
  border-bottom: 1px solid #eee;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #1f2329;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  color: #4e5969;
}

/* 状态标签样式 */
.status-tag {
  padding: 3px 8px;
  border-radius: 2px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.active {
  background-color: #f0f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.status-tag.inactive {
  background-color: #fff2f0;
  color: #ff4d4f;
  border-color: #ffccc7;
}

/* 状态选择按钮组 */
.status-radio-group {
  margin-top: 12px;
}

:deep(.status-radio-group .el-radio-button__inner) {
  border-radius: 4px;
  transition: all 0.2s ease;
}

:deep(.status-radio-group .el-radio-button.is-active .el-radio-button__inner) {
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 操作按钮样式 */
:deep(.el-table-column:last-child .el-button) {
  margin: 0 3px;
  padding: 5px 10px;
  border-radius: 4px;
  font-size: 12px;
  transition: all 0.2s ease;
}

:deep(.el-table-column:last-child .el-button):hover {
  transform: translateY(-1px);
}

/* 图标样式 */
:deep(.el-icon) {
  vertical-align: middle;
  margin-right: 4px;
}
</style>